// script.js

// 获取元素
const draggableWindow = document.getElementById("draggable-window");
const windowHeader = document.getElementById("window-header");
const toggleBtn = document.getElementById("toggle-btn");
const mapContainer = document.querySelector('.map-container');

// 设置窗口初始位置为右上角
const setInitialPosition = () => {
    const mapContainerRect = mapContainer.getBoundingClientRect();
    draggableWindow.style.left = mapContainerRect.right - draggableWindow.offsetWidth + 'px'; // 设置窗口的左边距
    draggableWindow.style.top = mapContainerRect.top + 'px'; // 设置窗口的上边距
};

// 初始化位置
setInitialPosition();

// 拖动功能
let isDragging = false;
let offsetX, offsetY;

// 监听鼠标按下事件，启用拖动
windowHeader.addEventListener("mousedown", (e) => {
    isDragging = true;
    offsetX = e.clientX - draggableWindow.offsetLeft;
    offsetY = e.clientY - draggableWindow.offsetTop;
    document.body.style.userSelect = 'none'; // 禁止文本选择
});

// 监听鼠标移动事件，更新窗口位置
document.addEventListener("mousemove", (e) => {
    if (isDragging) {
        // 获取容器的边界和滚动位置
        const mapContainerRect = mapContainer.getBoundingClientRect();
        const windowRect = draggableWindow.getBoundingClientRect();

        // 计算新的位置
        let posX = e.clientX - offsetX;
        let posY = e.clientY - offsetY;

        // 获取页面滚动的偏移
        const scrollX = window.scrollX;
        const scrollY = window.scrollY;

        // 限制窗口的 x 和 y 坐标不超出容器的边界
        const minLeft = mapContainerRect.left + scrollX;
        const maxLeft = mapContainerRect.right + scrollX - windowRect.width;
        const minTop = mapContainerRect.top + scrollY;
        const maxTop = mapContainerRect.bottom + scrollY - windowRect.height;

        // 更新窗口的位置，确保它在容器范围内
        posX = Math.max(minLeft, Math.min(posX, maxLeft));
        posY = Math.max(minTop, Math.min(posY, maxTop));

        draggableWindow.style.left = posX + "px";
        draggableWindow.style.top = posY + "px";
    }
});

// 监听鼠标释放事件，结束拖动
document.addEventListener("mouseup", () => {
    isDragging = false;
    document.body.style.userSelect = ''; // 恢复文本选择
});

// 点击切换收缩/展开窗口内容
toggleBtn.addEventListener("click", () => {
    draggableWindow.classList.toggle("collapsed");
});

// 监听窗口大小变化时重新设置初始位置
window.addEventListener('resize', () => {
    setInitialPosition();
});
